<?php

class ModelDescriptor extends EventDispatcher {
	private $_name;
	public function getName(){
		return $this->_name;
	}
	/**
	 * Enter description here...
	 *
	 * @var Config
	 */
	private $_config;
	private $_classPath;
	private $_fields;
	private $_table;
	private $_className;
	public function __construct(){
		$this->_config=Application::getAppInstance()->getConfig();
		$this->_classPath = $this->_config->get("config.model.classPath",$this->_classPath);
		$this->addEventListener(ModelDescriptorEvent::FIELDS_ADDED,new EventListener($this,"init"));
		$this->_className = get_class($this);
		//var_dump($this->_className);
		//echo "<br />!!!!";
	}
	
	public function setFields($fields){
		$this->dispatchEvent(new ModelDescriptorEvent(ModelDescriptorEvent::FIELDS_ADDED,$fields));
	}
	
	public function init(ModelDescriptorEvent $event){
		$fields = $event->getFields();
		$descriptor = new TableDescriptor(get_class($this),DriverManager::getConnection($this->_config->get("config.db.uri")));
		$this->_table=$descriptor->createTable();				
	}
	
	private function _initByPk($pk){
		$this->_table->init($pk);
	}
	
	public function getByPk($value){
		$class = $this->_className;
		$newDescriptor = new $class();
		$newDescriptor->_initByPk($value);
		return $newDescriptor;
	}
	
	public function save(){
		
	}
	
	public function delete(){
		
	}
	
	public function __get($name){
		return $this->_table->$name;
	}
	public function __set($name,$value){
		$this->_table->$name=$value;
	}
	
}
class ModelDescriptorEvent extends Event {
	const FIELDS_ADDED="fieldsEddedEvent";
	private $_fields;
	/**
	 * Enter description here...
	 *
	 * @return array
	 */
	public function getFields(){
		return $this->_fields;
	}
	public function __construct($type,$fields){
		parent::__construct($type);
		$this->_fields = $fields;
	}
}
?>